const express = require('express')
const cors = require('cors')
const path = require('path')
require('dotenv').config()

// 引入路由
const userRoutes = require('./routes/userRoutes')
const productRoutes = require('./routes/productRoutes')
const cartRoutes = require('./routes/cartRoutes')
const orderRoutes = require('./routes/orderRoutes')
const adminRoutes = require('./routes/adminRoutes')

// 引入中间件
const errorHandler = require('./middleware/errorHandler')

const app = express()

// CORS配置 - 允许跨域请求
app.use(cors({
  origin: [
    'http://localhost:5173', 
    'http://127.0.0.1:5173', 
    'http://localhost:5174', 
    'http://127.0.0.1:5174',
    'http://localhost:3100',  // 管理后台端口
    'http://127.0.0.1:3100'
  ],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['Content-Range', 'X-Content-Range']
}))

// 解析JSON和URL编码的请求体
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

// 静态文件服务 - 提供上传的图片访问
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))

// 静态文件服务 - 提供管理后台页面访问
app.use(express.static(path.join(__dirname, 'public')))

// 请求日志
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`)
  next()
})

// 健康检查接口
app.get('/', (req, res) => {
  res.json({
    code: 200,
    message: '京东商城API服务运行中',
    timestamp: new Date().toISOString()
  })
})

// 挂载路由
app.use('/api/user', userRoutes)
app.use('/api/product', productRoutes)
app.use('/api/cart', cartRoutes)
app.use('/api/order', orderRoutes)
app.use('/api/admin', adminRoutes)

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在',
    path: req.path
  })
})

// 错误处理中间件（必须放在最后）
app.use(errorHandler)

module.exports = app






